package team.umbc;

import java.util.ArrayList;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class FriendActivity extends Activity  implements OnClickListener{

	FriendsDB dbHelper;
	SQLiteDatabase db;
	Cursor cursor;
	ListView listTimeline;
	FriendAdapter adapter;
	Facebook facebook;
	private SharedPreferences settings;
	private static ArrayList<String> selectedIDs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_list);
		selectedIDs = new ArrayList<String>(5);
		
		// Find your views
		listTimeline = (ListView) findViewById(R.id.friendList);

		settings = getSharedPreferences(CheckinActivity.PREFS_NAME, 0);
		// Setting up Facebook
		facebook = new Facebook(CheckinActivity.APP_ID);
		facebook.setAccessToken(settings.getString(CheckinActivity.ACCESS_TOKEN, ""));
		facebook.setAccessExpires(settings.getLong(CheckinActivity.EXPIRES_IN, 0));
		
		// Connect to database
		dbHelper = new FriendsDB(this);
		db = dbHelper.getReadableDatabase();
		
		if (facebook.isSessionValid()) {
			startService(new Intent(this, FriendService.class));
		} else {
			facebook.authorize(this, new String[] { "publish_checkins",
					"read_friendlists", "offline_access" },
					new DialogListener() {
						@Override
						public void onComplete(Bundle values) {
							
						}

						@Override
						public void onFacebookError(FacebookError error) {
						}

						@Override
						public void onError(DialogError e) {
						}

						@Override
						public void onCancel() {
						}
					});
		}
		
	}
	
	@Override  
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	        facebook.authorizeCallback(requestCode, resultCode, data);  
	}

	@Override
	public void onDestroy() {

		super.onDestroy();
		// Close the database
		db.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// Get the data from the database
		cursor = db.query(FriendsDB.TABLE, null, null, null, null, null,
				FriendsDB.F_NAME + " ASC");
		startManagingCursor(cursor);

		// Create the adapter
		adapter = new FriendAdapter(this, cursor); //
		listTimeline.setAdapter(adapter); //
	}
	
	@Override
	public void onClick(View view) {
		Editor editor = settings.edit();
		String id = (String) view.getTag();
		String newName = " " + view.getTag() + ",";
		String names = settings.getString("friend", "");
		
		//if there are no friends already selected
		if(names.equals("")){
			names = newName;
			editor.putString("friend", names);
			selectedIDs.add(id);
			view.setBackgroundColor(Color.GREEN);
		//if there are friends already selected	
		} else {
			//if the friend has already been selected
			if(names.contains(newName)){
				names = names.replace(newName, "");
				view.setBackgroundColor(Color.DKGRAY);
				selectedIDs.remove(id);
			//if the friend hasn't already been selected	
			} else {
				names = newName + names;
				selectedIDs.add(id);
				view.setBackgroundColor(Color.GREEN);
			}
			editor.putString("friend", names);
		}
		editor.commit();
	}
	
	public static class FriendAdapter extends SimpleCursorAdapter{ //

		static final String[] FROM = { FriendsDB.F_NAME, FriendsDB.F_FB_ID }; //
		static final int[] TO = { R.id.friendName, R.id.friendID }; //
		private Context context;
		String id;

		public FriendAdapter(Context context, Cursor c) { //
			super(context, R.layout.friend_row, c, FROM, TO);
			this.context = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			super.getView(position, convertView, parent);
			
			if (null == convertView) {
				LayoutInflater inflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.friend_row, null);
			}
			
			LinearLayout layout = (LinearLayout)convertView.findViewById(R.id.friendLayout);
			TextView id = (TextView) convertView.findViewById(R.id.friendID);
			TextView name = (TextView) convertView.findViewById(R.id.friendName);
			
			String idText = (String)id.getText();
			
			layout.setTag(idText);
			layout.setOnClickListener((OnClickListener) context);
			
			// change the row color based on selected state
	        if(selectedIDs.contains(idText)){
	        	layout.setBackgroundColor(Color.GREEN);
	        } else {
	        	layout.setBackgroundColor(Color.DKGRAY);
	        }

			return convertView;
		}

		@Override
		public void bindView(View row, Context context, Cursor cursor) { //
			super.bindView(row, context, cursor);
		}
		
	}
}
